#include "pluginbase.h"
#include "account.h"

#include <QSettings>
#include <QLibrary>

PluginBase::PluginBase(QObject *parent) :
    QObject(parent)
{
}

PluginConfigBase::PluginConfigBase(PluginBase* plugin)
    : state(0), oldState(0)
{
    this->plugin = plugin;
}








PluginManager* PluginManager::me = NULL;

PluginBase* PluginManager::plugin(QString name)
{
    return pluginMap.value(name);
}

bool PluginManager::registerPlugin(PluginBase* plugin)
{
    if(!plugin)
        return false;
    if(pluginMap.contains(plugin->pluginName))
        return false;
    pluginMap[plugin->pluginName] = plugin;
    return true;
}

bool PluginManager::removePlugin(QString name)
{
    PluginBase* plugin;
    if(pluginMap.contains(name))
    {
        plugin = pluginMap.take(name);
        delete plugin;
        return true;
    }
    return false;
}

void PluginManager::load(Account* act)
{
    QMap<QString, PluginBase*>::Iterator it = pluginMap.begin();
    while(it != pluginMap.end())
    {
        PluginBase* plugin = *it;
        plugin->singleLoad(settings, act);
        ++it;
    }
}

void PluginManager::save(Account* act)
{
    QMap<QString, PluginBase*>::Iterator it = pluginMap.begin();
    while(it != pluginMap.end())
    {
        PluginBase* plugin = *it;
        plugin->singleSave(settings, act);
        ++it;
    }
}

QMap<QString, ConfigWidgetBase*> PluginManager::createConfigWidgets(Account* act)
{
    QMap<QString, ConfigWidgetBase*> ret;
    QMap<QString, PluginBase*>::Iterator it = pluginMap.begin();
    while(it != pluginMap.end())
    {
        PluginBase* plugin = *it;
        if(plugin->pluginName == "Login")
        {
            ++it;
            continue;
        }
        ret[plugin->pluginName] = plugin->createConfigWidget(act);
        ++it;
    }
    return ret;
}

int PluginManager::loadPlugins()
{
    /*
    uint ver = 0;
    char* name = NULL;
    QLibrary lib("test.dll");
    lib.setLoadHints(QLibrary::ResolveAllSymbolsHint);
    if(lib.load() == false)
        return 0;
    name = *(char**)lib.resolve("PLUGIN_NAME");
    ver = *(uint*)lib.resolve("PLUGIN_VERSION");
    */
    return 0;
}


PluginManager* PluginManager::self()
{
    return me?me : (me = new PluginManager());
}

PluginManager::PluginManager()
{

}

PluginManager::~PluginManager()
{

}

ConfigWidgetBase::ConfigWidgetBase(PluginConfigBase* cfg, QWidget* parent)
    : QWidget(parent)
{
    this->cfg = cfg;
}


